package com.jt.assistant.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.cl.picture_selector.ImagePicker
import com.google.gson.reflect.TypeToken
import com.jt.assistant.R
import com.jt.assistant.adapter.JDDialogListAdapter
import com.jt.assistant.adapter.PicAdapter
import com.jt.assistant.bean.CityBean
import com.jt.assistant.bean.ForwarderListBean
import com.jt.assistant.bean.Param
import com.jt.assistant.bean.WaybillCityBean
import com.jt.assistant.custom_view.ItemEdit
import com.jt.assistant.utils.GlideLoader
import com.jt.assistant.viewmodel.HomeViewModel
import com.jt.assistant.base.GlobalConfig
import com.jt.assistant.base.GlobalConfig.PIC_REQUEST
import com.jt.assistant.base.GlobalConfig.REQUEST_SELECT_IMAGES_CODE
import com.orhanobut.logger.Logger
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_gx.*
import kotlinx.android.synthetic.main.activity_gx.bt_commit
import kotlinx.android.synthetic.main.activity_gx.ie_remark
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File


/**
 * 干线运单登记
 */
class GxActivity : BaseActivity<HomeViewModel>() {
    private val mAdapter by lazy {
        PicAdapter(
            ArrayList<String>()
        )
    }

    private val maxPicCount = 10//最大图片选择数量

    var mForwarderList = ArrayList<ForwarderListBean>()
    var mCityList = ArrayList<CityBean>()


    override fun layoutId(): Int = R.layout.activity_gx

    override fun initView(savedInstanceState: Bundle?) {
        ie_cartonNum.mEdit.inputType =
            InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        ie_volume.mEdit.inputType =
            InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        ie_charge.mEdit.inputType =
            InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        with(rv_gx) {
            layoutManager = GridLayoutManager(context, 3)
            canScrollVertically(0)
            adapter = mAdapter
            mAdapter.data.add("")
            mAdapter.notifyDataSetChanged()
        }
    }

    override fun initData() {
        viewModel.forwarderList()
        viewModel.getStoreCityList()

        ie_orientation.mData.add("送仓")
        ie_orientation.mData.add("退仓")
        ie_orientation.setEditText("送仓")

    }

    override fun initListener() {
        netListener()

        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (mAdapter.data[position].isEmpty()) {
                ImagePicker.getInstance()
                    .setTitle("标题") //设置标题
                    .showCamera(true) //设置是否显示拍照按钮
                    .showImage(true) //设置是否展示图片
                    .showVideo(true) //设置是否展示视频
                    .showLoading(true, "请稍后...")
                    .setMaxCount(maxPicCount - mAdapter.itemCount + 1) //设置最大选择图片数目(默认为1，单选)
                    .setSingleType(true) //设置图片视频不能同时选择
                    .setImageLoader(GlideLoader()) //设置自定义图片加载器
                    .start(
                        this@GxActivity,
                        REQUEST_SELECT_IMAGES_CODE
                    ) //REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode
            } else {//预览图
                startActivityForResult(Intent(this@GxActivity, PreActivity::class.java).apply {
                    putExtra("IMAGEPATH", GsonUtils.toJson(mAdapter.data))
                    putExtra("POSITION", position)
                }, PIC_REQUEST)
            }

        }

        ie_ForwarderList.mEdit.setOnClickListener {
            ie_ForwarderList.showListDialog("承运商选择", this)
        }


        ie_cityStart.mEdit.setOnClickListener {
            ie_cityStart.showListDialog("起点城市选择", this)
        }


        ie_cityEnd.mEdit.setOnClickListener {
            ie_cityEnd.showListDialog("终点城市选择", this)
        }


        ie_orientation.mEdit.setOnClickListener {
            ie_orientation.showListDialog("送仓退仓选择", this)
        }

        ie_orientation.setOnItemClickListener(object : ItemEdit.OnClickLister {
            override fun onItemClick(position: Int) {

            }
        })

        ie_jdSelect.mEdit.setOnClickListener {
            val params = Param::class.java.newInstance()
            params.forwarderId =
                mForwarderList[ie_ForwarderList.mCurrentPosition].forwarderId.toString()
            params.type = ie_orientation.mCurrentPosition.toString()
            params.cityId =
                if (params.type == "0")//0正向 1逆向 ie_cityStart
                    mCityList[ie_cityEnd.mCurrentPosition].cityId.toString()
                else
                    mCityList[ie_cityStart.mCurrentPosition].cityId.toString()
            viewModel.queryWaybillByCity(params)
        }


        bt_commit.setOnClickListener {
//            Logger.e(ie_gxCode.mEdit.text.toString()) //干线运单号
//            Logger.e(ie_orientation.mCurrentPosition.toString())  //送仓退仓
//            Logger.e(ie_cityStart.mEdit.text.toString()) //起点
//            Logger.e(ie_cityEnd.mEdit.text.toString()) //终点
//
//            Logger.e(ie_cartonNum.mEdit.text.toString()) //箱数
//            Logger.e(ie_volume.mEdit.text.toString()) //体积
//            Logger.e(ie_charge.mEdit.text.toString()) //运费
//            Logger.e(ie_remark.mEdit.text.toString()) //备注
//
//            Logger.e(mForwarderList[ie_ForwarderList.mCurrentPosition].forwarderId.toString()) //承运商
//            Logger.e(mJdList.toString())//渠道单号列表
//
//            Logger.e(mJdTotalNum.toString())//渠道单总箱数
            if (ie_gxCode.mEdit.text.toString().isEmpty()) {
                ToastUtils.showShort("请输入运单号")
                return@setOnClickListener
            }
            if (ie_cartonNum.mEdit.text.toString().isEmpty()) {
                ToastUtils.showShort("请输入箱码")
                return@setOnClickListener
            }
            if (ie_volume.mEdit.text.toString().isEmpty()) {
                ToastUtils.showShort("请输入体积")
                return@setOnClickListener
            }
            if (ie_charge.mEdit.text.toString().isEmpty()) {
                ToastUtils.showShort("请输入运费")
                return@setOnClickListener
            }
            if (mJdList.isEmpty()) {
                ToastUtils.showShort("请选择京东单号")
                return@setOnClickListener
            }

            if (ie_cityStart.mEdit.text.toString() == ie_cityEnd.mEdit.text.toString()) {
                ToastUtils.showShort("起点与终点不能相同")
                return@setOnClickListener
            }

            if (ie_cartonNum.mEdit.text.toString() != mJdTotalNum) {
                ToastUtils.showShort("箱码数异常")
                return@setOnClickListener
            }

            if (mAdapter.data.size == 1) {
                ToastUtils.showShort("请选择图片")
                return@setOnClickListener
            }

            val params = Param::class.java.newInstance()
            params.forwarderCarCode = ie_gxCode.mEdit.text.toString().trim()
            params.type = ie_orientation.mCurrentPosition.toString().trim()//0出仓 1退仓
            params.start = ie_cityStart.mEdit.text.toString().trim()
            params.end = ie_cityEnd.mEdit.text.toString().trim()
            params.volume = ie_volume.mEdit.text.toString().trim()
            params.cartonNum = ie_cartonNum.mEdit.text.toString().trim()
            params.forwarderId =
                mForwarderList[ie_ForwarderList.mCurrentPosition].forwarderId.toString().trim()
            params.charge = ie_charge.mEdit.text.toString().trim()
            params.waybillList = mJdList
            params.remark = ie_remark.mEdit.text.toString().trim()

            viewModel.uploadForwarderWaybill(params, mAdapter.data)

        }
    }


    private fun netListener() {
        viewModel.mForwarderList.observe(this, {
            if (it.isSuccess()) {
                mForwarderList.clear()
                mForwarderList.addAll(it.data)
                ie_ForwarderList.setEditText(it.data[0].forwarderName)
                it.data.forEach {
                    ie_ForwarderList.mData.add(it.forwarderName)
                }
            }
        })

        viewModel.mGetStoreCityList.observe(this, {
            if (it.isSuccess()) {
                mCityList.clear()
                mCityList.addAll(it.data)
                ie_cityStart.setEditText(it.data[0].cityName)
                ie_cityEnd.setEditText(it.data[0].cityName)
                it.data.forEach {
                    ie_cityStart.mData.add(it.cityName)
                    ie_cityEnd.mData.add(it.cityName)
                }
            }
        })

        viewModel.mQueryWaybillByCity.observe(this, {
            if (it.isSuccess()) {
                showJDDialog("京东采购单列表", it.data)
            }
        })

        viewModel.mUploadForwarderWaybill.observe(this, {
            if (it.isSuccess()) {
                speakString("上传成功")
                finish()
            }
        })

    }

    var mJdTotalNum = ""
    var mJdList = ArrayList<String>()

    private fun showJDDialog(title: String, listData: MutableList<WaybillCityBean>) {
        val dialog = MaterialDialog(this).show {
            title(text = title)
            customView(
                R.layout.layout_dialog_jd_list,
                scrollable = false,
                horizontalPadding = false
            )
            lifecycleOwner(this@GxActivity)
        }
        // Setup custom view content
        val customView = dialog.getCustomView()
        val rvDialog: RecyclerView = customView.findViewById(R.id.rv_dialog)
        val check: ImageView = customView.findViewById(R.id.jd_check_iv)
        val cartonNum: TextView = customView.findViewById(R.id.carton_num_tv)
        val oneKey: RelativeLayout = customView.findViewById(R.id.rl_oneKey)
        val cancel: TextView = customView.findViewById(R.id.tv_cancle)
        val commit: TextView = customView.findViewById(R.id.tv_commit)
        val listAdapter = JDDialogListAdapter(ArrayList<WaybillCityBean>())
        check.load(R.mipmap.icon_uncheck)

        cancel.setOnClickListener { dialog.dismiss() }
        commit.setOnClickListener {
            //运单号List  总箱码
            mJdList.clear()
            mJdTotalNum = cartonNum.text.toString()

            listAdapter.data.forEach {
                if (it.isChoose)
                    mJdList.add(it.channelOrderNo)
            }

            if (mJdList.isEmpty())
                ie_jdSelect.setEditText("")
            else
                ie_jdSelect.setEditText("已选择(${getTotleNum(listAdapter.data)}箱)")

            dialog.dismiss()

        }

        oneKey.setOnClickListener {
            var isChoose = isAllChoose(listAdapter.data)

            listAdapter.data.forEach {
                it.isChoose = !isChoose
            }
            listAdapter.notifyDataSetChanged()
            cartonNum.text = getTotleNum(listAdapter.data).toString()

            isChoose = isAllChoose(listAdapter.data)
            if (isChoose) check.load(R.mipmap.icon_checked) else check.load(R.mipmap.icon_uncheck)
        }

        with(rvDialog) {
            layoutManager = LinearLayoutManager(context)
            adapter = listAdapter
            listAdapter.data.addAll(listData)
            listAdapter.notifyDataSetChanged()
        }

        listAdapter.setOnItemClickListener { adapter, view, position ->
            listAdapter.data[position].isChoose = !listAdapter.data[position].isChoose
            listAdapter.notifyDataSetChanged()

            cartonNum.text = getTotleNum(listAdapter.data).toString()
            val isChoose = isAllChoose(listAdapter.data)
            if (isChoose) check.load(R.mipmap.icon_checked) else check.load(R.mipmap.icon_uncheck)
        }
    }

    private fun getTotleNum(data: MutableList<WaybillCityBean>): Int {
        var totalNum = 0
        data.forEach {
            if (it.isChoose)
                totalNum += it.cartonNum
        }
        return totalNum
    }

    private fun isAllChoose(data: MutableList<WaybillCityBean>): Boolean {
        data.forEach {
            if (!it.isChoose) return false
        }
        return true
    }


    private fun imagePick(mImagePaths: ArrayList<String>?) {
        Luban.with(this)
            .load<String>(mImagePaths)
            .ignoreBy(100)
//            .setTargetDir(ImageUtil.getPath())
            .setFocusAlpha(false)
            .filter { path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")) }
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {}

                @SuppressLint("SetTextI18n")
                override fun onSuccess(file: File) {
                    Logger.e(file.absolutePath)
                    mAdapter.data.add(0, file.absolutePath)
                    mAdapter.notifyDataSetChanged()
                    if ((mAdapter.data.size - 1) == maxPicCount) {
                        mAdapter.data.remove("")
                        mAdapter.notifyDataSetChanged()
                    }
                }

                override fun onError(e: Throwable) {

                }
            }).launch()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            imagePick(data!!.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES))
        }

        if (requestCode == PIC_REQUEST && resultCode == RESULT_OK) {
            val picList = GsonUtils.fromJson<ArrayList<String>>(
                data!!.getStringExtra(GlobalConfig.PIC_RESULT),
                object : TypeToken<ArrayList<String>>() {}.type
            )
            imagePickPre(picList)
        }
    }

    private fun imagePickPre(picList: ArrayList<String>?) {
        mAdapter.data.clear()
        if (picList!!.isNotEmpty()) {
            mAdapter.data.addAll(picList)
        }
        mAdapter.data.add("")
        if ((mAdapter.data.size - 1) == maxPicCount) {
            mAdapter.data.remove("")
        }
        mAdapter.notifyDataSetChanged()
    }


}